<!DOCTYPE html><html lang="zh" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>volatile和变量模型 | 百丽宫一只懒猫的小窝</title><meta name="keywords" content="计算机结构"><meta name="author" content="杜书丞"><meta name="copyright" content="杜书丞"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="想要让处理器对变量的值进行操作，还需要经过一道门槛">
<meta property="og:type" content="article">
<meta property="og:title" content="volatile和变量模型">
<meta property="og:url" content="https://devil-sx.github.io/2023/01/C++/volatile%E5%92%8C%E5%8F%98%E9%87%8F%E6%A8%A1%E5%9E%8B/index.html">
<meta property="og:site_name" content="百丽宫一只懒猫的小窝">
<meta property="og:description" content="想要让处理器对变量的值进行操作，还需要经过一道门槛">
<meta property="og:locale">
<meta property="og:image" content="https://devil-sx.github.io/linear-gradient(20deg,#334d50,#cbcaa5)">
<meta property="article:published_time" content="2023-01-05T16:39:01.000Z">
<meta property="article:modified_time" content="2023-01-26T07:13:01.505Z">
<meta property="article:author" content="杜书丞">
<meta property="article:tag" content="计算机结构">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://devil-sx.github.io/linear-gradient(20deg,#334d50,#cbcaa5)"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://devil-sx.github.io/2023/01/C++/volatile%E5%92%8C%E5%8F%98%E9%87%8F%E6%A8%A1%E5%9E%8B/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="baidu-site-verification" content="code-yPfTRU4FS9"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'volatile和变量模型',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-01-26 15:13:01'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/ali_icon.css"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">17</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">11</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">7</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background: linear-gradient(20deg,#334d50,#cbcaa5)"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">百丽宫一只懒猫的小窝</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">volatile和变量模型</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2023-01-05T16:39:01.000Z" title="Created 2023-01-06 00:39:01">2023-01-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2023-01-26T07:13:01.505Z" title="Updated 2023-01-26 15:13:01">2023-01-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/C/">C++</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">Word count:</span><span class="word-count">880</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">Reading time:</span><span>2min</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="volatile和变量模型"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/hint.css/2.4.1/hint.min.css"><p>学习<a target="_blank" rel="noopener" href="https://github.com/liangkangnan/tinyriscv">tinyrisc-v项目</a>运行程序时出现Time Out的输出。对比测试锁定在了volatile关键字上。发现像示例一样声明变量时加上volatile就解决了。之前也接触过volatile的相关资料，当时似懂非懂，借这次机会捣鼓一下。</p>
<p>以例程里的计时器中断文件举例：<code>/tests/example/timer_int/main.c</code></p>
<p><img src="main.png" alt="main.c"><br><em>注：在同目录的<code>Makefile</code>文件下可以看到<img src="CFLAG.png" alt="">这个参数，预定义了<code>SIMULATION</code>，只会编译<code>#ifdef SIMULATION</code>中的代码</em></p>
<h3 id="Volatile-优化了什么？"><a href="#Volatile-优化了什么？" class="headerlink" title="Volatile 优化了什么？"></a>Volatile 优化了什么？</h3><p>我们仅仅修改<code>count</code>变量声明，一次保留<code>volatile</code>，一次去掉，分别编译，对比生成的反汇编文件<code>timer_int.dump</code></p>
<p><img src="diff.png" alt="左侧是去掉volatile，右侧是保留volatile">  </p>
<p>程序出现了超时问题(Time Out)，因此我们重点关注循环的条件判断观察是否导致离死循环——也就是源文件<code>main.c</code>的 <code>if(count == 2)</code> 语句</p>
<p>条件判断在汇编里对应的是条件分支指令，也就是反编译中出现的 <strong>bne</strong>。</p>
<pre><code>bne（branch not equal）作用是对比两个寄存器的值，如果不等即跳转到指定的程序位置。
</code></pre><p>两次bne的区别是跳转的位置不同，去掉关键字后是跳转到<code>9c</code>——本行，而保留是跳转到<code>98</code>——上一行。我们来看看这<code>98</code>标签的程序。</p>
<p><code>98</code>是：<strong>lw a3,0(a5)</strong></p>
<pre><code>lw(Load Word)，从内存中取数据到寄存器之中
</code></pre><p>从a5（基地址,Base）+0（偏移量,offset）的地址对应的内存中，取出字放在a3寄存器内。a5是0x10000&lt;&lt;12（左移12位来自<code>lui</code>，Load Upper Immediate），是编译器为变量分配的基地址，而0(a5)则存放着count变量</p>
<p>也就是说，每次进行循环判断时，保留volatile会重新从内存中取出count的值放入寄存器中进行比较，而去掉后则不会更新寄存器进行比较，所以导致寄存器中的值始终不变，进入死循环</p>
<h3 id="为什么会优化？"><a href="#为什么会优化？" class="headerlink" title="为什么会优化？"></a>为什么会优化？</h3><p>处理器能对寄存器之中的值进行运算处理，所以储存在寄存器中的变量运算最快。</p>
<div class="mermaid-wrap"><pre class="mermaid-src" hidden>
  flowchart LR
a[处理器]&lt;--&gt; b[寄存器]
  </pre></div>
<p>但为了控制数据传输的开支，寄存器的数量是有限的，若变量数量超出寄存器数量，编译器就会将一部分变量储存在内存之中。</p>
<p>处理器不能直接对内存中的值进行操作，因此如果要对内存中的值进行处理，要先把内存的值放在寄存器之中。</p>
<div class="mermaid-wrap"><pre class="mermaid-src" hidden>
  flowchart LR
a[处理器]&lt;--&gt; b[寄存器]&lt;--&gt;c[内存]
  </pre></div>
<p>而若两次指令的过程中，编译器判断某个变量的值没有发生变化，便会省去从内存中取值的操作，使用上一次的值进行计算。</p>
<p>那么volatile的作用是什么呢？</p>
<p><a target="_blank" rel="noopener" href="https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf">C17</a>标准中对于voliate的说明：</p>
<p><img src="C17.png" alt=""></p>
<p>volatile类型的变量可能受某些执行或副作用修改，使用volatile将严格使用abstract machine（定义也在C17中）的规则评估（操作它的行为）。</p>
<p>count变量的更新是在中断之中执行的，在编译阶段中无法“察觉”到这个更新，于是编译器认为count变量没有发生变化，进行了优化。使用volatile关键字则可以强制每次使用count从内存中取值。</p>
<h3 id="还有一些搞不懂的地方"><a href="#还有一些搞不懂的地方" class="headerlink" title="还有一些搞不懂的地方"></a>还有一些搞不懂的地方</h3><p>反汇编指令中出现了mv a5,a5，这个指令有什么作用？能去掉吗？</p>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BB%93%E6%9E%84/">计算机结构</a></div><div class="post_share"><div class="social-share" data-image="/linear-gradient(20deg,#334d50,#cbcaa5)" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> Donate</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/Wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/img/Wechat.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li></ul></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> Comment</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81NzU3OS8zNDA0Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Volatile-%E4%BC%98%E5%8C%96%E4%BA%86%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-number">1.</span> <span class="toc-text">Volatile 优化了什么？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BC%9A%E4%BC%98%E5%8C%96%EF%BC%9F"><span class="toc-number">2.</span> <span class="toc-text">为什么会优化？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%98%E6%9C%89%E4%B8%80%E4%BA%9B%E6%90%9E%E4%B8%8D%E6%87%82%E7%9A%84%E5%9C%B0%E6%96%B9"><span class="toc-number">3.</span> <span class="toc-text">还有一些搞不懂的地方</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By 杜书丞</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Toggle Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="Scroll To Comments"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"><script>(() => {
  const $mermaidWrap = document.querySelectorAll('#article-container .mermaid-wrap')
  if ($mermaidWrap.length) {
    window.runMermaid = () => {
      window.loadMermaid = true
      const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default'

      Array.from($mermaidWrap).forEach((item, index) => {
        const mermaidSrc = item.firstElementChild
        const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n'
        const mermaidID = 'mermaid-' + index
        const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent
        mermaid.mermaidAPI.render(mermaidID, mermaidDefinition, (svgCode) => {
          mermaidSrc.insertAdjacentHTML('afterend', svgCode)
        })
      })
    }

    const loadMermaid = () => {
      window.loadMermaid ? runMermaid() : getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaid)
    }

    window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
  }
})()</script><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>